from sqlalchemy.ext.asyncio import AsyncSession

from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_stock.dao.account_dao import AccountDao
from module_stock.dao.transfer_dao import TransferDao
from module_stock.entity.vo.account_vo import AccountPageQueryModel
from module_stock.entity.vo.transfer_vo import DeleteTransferModel, TransferModel, TransferPageQueryModel
from utils.common_util import CamelCaseUtil


class TransferService:
    """
    银证转账模块服务层
    """

    @classmethod
    async def get_transfer_list_services(
            cls, query_db: AsyncSession, query_object: TransferPageQueryModel, is_page: bool = False
    ):
        """
        获取银证转账列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 银证转账列表信息对象
        """
        transfer_list_result = await TransferDao.get_transfer_list(query_db, query_object, is_page)

        return transfer_list_result

    @classmethod
    async def add_transfer_services(cls, query_db: AsyncSession, page_object: TransferModel):
        """
        新增银证转账信息service

        :param query_db: orm对象
        :param page_object: 新增银证转账对象
        :return: 新增银证转账校验结果
        """
        try:
            await TransferDao.add_transfer_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_transfer_services(cls, query_db: AsyncSession, page_object: TransferModel):
        """
        编辑银证转账信息service

        :param query_db: orm对象
        :param page_object: 编辑银证转账对象
        :return: 编辑银证转账校验结果
        """
        edit_transfer = page_object.model_dump(exclude_unset=True, exclude={'create_time', })
        transfer_info = await cls.transfer_detail_services(query_db, page_object.id)
        if transfer_info.id:
            try:
                await TransferDao.edit_transfer_dao(query_db, edit_transfer)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='银证转账不存在')

    @classmethod
    async def delete_transfer_services(cls, query_db: AsyncSession, page_object: DeleteTransferModel):
        """
        删除银证转账信息service

        :param query_db: orm对象
        :param page_object: 删除银证转账对象
        :return: 删除银证转账校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await TransferDao.delete_transfer_dao(query_db, TransferModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入主键ID为空')

    @classmethod
    async def transfer_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取银证转账详细信息service

        :param query_db: orm对象
        :param id: 主键ID
        :return: 主键ID对应的信息
        """
        transfer = await TransferDao.get_transfer_detail_by_id(query_db, id=id)
        if transfer:
            result = TransferModel(**CamelCaseUtil.transform_result(transfer))
        else:
            result = TransferModel(**dict())

        return result

    @classmethod
    async def get_transfer_amount_by_account_tag_services(cls, query_db: AsyncSession):
        """
        根据账号标签统计转账金额service

        :param query_db: orm对象
        :return: 按账号标签统计的转账金额列表
        """
        account_list = await AccountDao.get_account_list(query_db, AccountPageQueryModel(), is_page=False)
        account_tags = list(set(account['accountTag'] for account in account_list if account.get('accountTag')))

        result = {}
        for account_tag in account_tags:
            accounts_with_tag = [account for account in account_list if account.get('accountTag') == account_tag]
            account_nos = [account['accountNo'] for account in accounts_with_tag]
            amount_sum = await TransferDao.get_transfer_amount_by_account_nos(query_db, account_nos)
            result[account_tag] = float(amount_sum) if amount_sum else 0.0

        return result
